package com.hqu.jim.tool;

import com.hqu.jim.entity.Attendance;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FileTool {
    public List<Attendance> readFile(String fileName){
        List<Attendance> attendances = new ArrayList<>();
        try{
            //获取文件绝对路径
            String path = this.getClass().getClassLoader().getResource("/com/hqu/jim/dataFiles/"+fileName).getPath();
            File file = new File(path);
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "gbk");
            BufferedReader bReader = new BufferedReader(isr);
            String temp = "";
            while ((temp = bReader.readLine())!=null && temp.length()>1){
                String[] temps =temp.split(",");
                Attendance attendance = new Attendance();
                attendance.setId(temps[0]);
                attendance.setStatus(temps[1]);
                attendance.setSequence(temps[2]);
                attendance.setName(temps[3]);
                attendance.setMarks(Arrays.copyOfRange(temps,4,temps.length));
                attendances.add(attendance);
            }
            bReader.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return attendances;
    }

    public boolean writeFile(String fileName,List<Attendance> attendances){
        try {
            String path = this.getClass().getClassLoader().getResource("/com/hqu/jim/dataFiles/"+fileName).getPath();
            File file = new File(path);
            OutputStreamWriter osw =new OutputStreamWriter(new FileOutputStream(file),"gbk");
            BufferedWriter bWriter = new BufferedWriter(osw);
            String temp = "";
            for (Attendance a:attendances) {
                temp = a.toString();
                bWriter.write(temp);
                bWriter.newLine();
            }
            bWriter.flush();
            bWriter.close();
            return true;
        }
        catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}